﻿using Anke.SHManage.BLL;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace Anke.SHManage.Web.Areas.DM.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /DM/User/
        [HttpGet]
        public ActionResult Index()
        {
            UserOperateContext userOperateContext = new UserOperateContext();
            bool Insert = userOperateContext.getGongneng(1327);////判断登录人有无新增权限
            if (Insert)
            {
                this.ViewData["PersonInsert"] = "1";//登录人有新增的权限
            }
            bool Edit = userOperateContext.getGongneng(1328);////判断登录人有无修改权限
            if (Edit)
            {
                this.ViewData["PersonEdit"] = "1";//登录人有修改的权限
            }
            bool Delete = userOperateContext.getGongneng(1329);////判断登录人有无删除权限
            if (Delete)
            {
                this.ViewData["PersonDelete"] = "1";//登录人有删除的权限
            }
            bool FenPei = userOperateContext.getGongneng(1330);////判断登录人有无分配部门角色权限
            if (FenPei)
            {
                this.ViewData["PersonFenPei"] = "1";//登录人有分配的权限
            }
            bool UpdatePwd = userOperateContext.getGongneng(1334);////判断登录人有无改密码权限
            if (UpdatePwd)
            {
                this.ViewData["PersonUpdatePwd"] = "1";//登录人有改密码的权限
            }
            bool all = userOperateContext.getGongneng(1331);//看所有人
            bool dep = userOperateContext.getGongneng(1332);//看所属部门人
            bool sel = userOperateContext.getGongneng(1333);//看自己
            if (all)
                this.ViewData["SearchBound"] = "all";
            else if (dep)
                this.ViewData["SearchBound"] = "dep";
            else
                this.ViewData["SearchBound"] = "sel";
            return View();
        }

        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            //0.接收参数 page=1&rows=5
            int pageIndex = int.Parse(form["page"]);
            int pageSize = int.Parse(form["rows"]);

            string strWorkCode = form["WorkCode"];
            string strName = form["Name"];
            string SearchBound = form["SearchBound"];
            #region 拼接查询条件
            //Expression<Func<P_User, bool>> where = p => p.IsActive == true;
            //Expression<Func<P_User, bool>> where = p => p.IsActive == p.IsActive;
            //if (strWorkCode != null && strWorkCode.Length > 0)
            //{
            //    where = where.And(r => r.WorkCode == strWorkCode);
            //}
            //if (strName != null && strName.Length > 0)
            //{
            //    where = where.And(s => s.Name.Contains(strName));
            //}
            #endregion
            string depIDs = "";
            UserOperateContext userOperateContext = new UserOperateContext();
            P_User uInfo = userOperateContext.Session_UsrInfo;
            List<TreeNode> listdep = new P_UserBLL().ToTreeNodes(uInfo.DepID.ToString(), "无");
            if (listdep != null && listdep.Count > 0)
            {
                foreach (TreeNode tr in listdep)
                { depIDs = depIDs + "," + tr.Value; }
            }
            if (depIDs.Length > 0)
                depIDs = depIDs.Substring(1);
            //1.读取数据
            var rowCount = 0;
            //var list = new P_UserBLL().GetPagedList(pageIndex, pageSize, ref rowCount, where, u => u.ID, true).Select(u => u.ToExtModle());
            var list = new P_UserBLL().GetUserList(pageIndex, pageSize, ref rowCount, strWorkCode, strName, SearchBound, uInfo.WorkCode, depIDs);
            //2.返回数据
            //return Json(new Model.EasyUIModel.DataGridModel() { total = rowCount, rows = list });
            return this.Json(list, "appliction/json", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult GetUserDepAndRole()
        {
            int userid = Convert.ToInt32(Request.Form["UserId"]);
            List<int> userRole = new P_UserRoleBLL().GetListBy(ur => ur.UserID == userid).Select(ur => ur.RoleID).ToList();
            P_User userInfo = new P_UserBLL().GetModelWithOutTrace(u => u.ID == userid);
            string Depid = "";
            if (userInfo != null)
            {
                Depid = userInfo.DepID.ToString();
            }
            string uRole = "";
            foreach (int item in userRole)
            {
                uRole = uRole + "," + item;
            }
            string reUR = "";
            if (uRole != "")
            {
                reUR = uRole.Substring(1);
            }
            return Json(new { UserRole = reUR, Dep = Depid }, "appliction/json", JsonRequestBehavior.AllowGet);
        }
        //取所有人员
        [HttpPost]
        public ActionResult GetUserList()
        {
            try
            {
                var list = new P_UserBLL().GetUserList();
                return this.Json(list);
            }
            catch
            {
                return this.Json("");
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserAdd()
        {
            string DetailInfo = Request.Form["Info"].ToString();
            List<P_User> list = new P_UserBLL().GetMaxID();

            P_User info = JsonHelper.GetJsonInfoBy<P_User>(DetailInfo);
            //新增人员时，限制重复工号的新增 add2024-10-17 plq
            P_User userInfo = new P_UserBLL().GetModelWithOutTrace(u => u.WorkCode == info.WorkCode && u.IsActive == true);
            if (userInfo != null)
            {
                return this.JsonResult(Utility.E_JsonResult.Error, "工号【" + info.WorkCode + "】的人员信息已存在，请勿重复新增!", null, null);
            }

            info.ID = list[0].ID + 1;
            info.PassWord = SecurityHelper.GetMD5(info.PassWord);
            info.IsActive = true;
            int res = new P_UserBLL().Add(info);
            if (res > 0)
                return this.JsonResult(Utility.E_JsonResult.OK, "保存成功！", null, null);
            else
                return this.JsonResult(Utility.E_JsonResult.Error, "保存失败", null, null);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserEdit()
        {

            string DetailInfo = Request.Form["Info"].ToString();
            P_User model = JsonHelper.GetJsonInfoBy<P_User>(DetailInfo);
            int res = new P_UserBLL().Modify(model, "DepID", "LoginName", "WorkCode", "Name", "Gender", "SN", "PhysicianCode", "YBCountryCode"); //add2022-03-28 plq  YBCountryCode字段

            if (res > 0)
                return this.JsonResult(Utility.E_JsonResult.OK, "修改成功！", null, null);
            else
                return this.JsonResult(Utility.E_JsonResult.Error, "修改失败", null, null);
        }

        /// <summary>
        ///  禁用/启用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserDisable()
        {
            int id = Convert.ToInt32(Request.Form["id"]);
            bool disable = Convert.ToBoolean(Request.Form["disable"]);
            P_User model = new P_User();
            model.IsActive = disable;
            model.ID = id;
            int res = new P_UserBLL().Modify(model, "IsActive");
            string tInfo = "";
            string finfo = "";
            if (disable)
            {
                tInfo = "设置“<span style='color:darkgreen'>有效</span>”成功！";
                finfo = "设置“<span style='color:darkgreen'>有效</span>”失败！";
            }
            else
            {
                tInfo = "设置“<span style='color:red'>无效</span>”成功！";
                finfo = "设置“<span style='color:red'>无效</span>”失败！";
            }
            if (res > 0)
                return this.JsonResult(Utility.E_JsonResult.OK, tInfo, null, null);
            else
                return this.JsonResult(Utility.E_JsonResult.Error, finfo, null, null);
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RePassword()
        {
            int usrId = int.Parse(Request.Form["uId"]);
            //获取部门id
            string newPwd = Request.Form["newPwd"].ToString();
            P_User model = new P_User();
            model.PassWord = SecurityHelper.GetMD5(newPwd);
            model.ID = usrId;
            int res = new P_UserBLL().Modify(model, "PassWord");
            if (res > 0)
                return this.JsonResult(Utility.E_JsonResult.OK, "新密码设置成功", null, null);
            else
                return this.JsonResult(Utility.E_JsonResult.Error, "新密码设置失败", null, null);
        }


        
        /// <summary>
        /// 获取带教人员下拉字典 （combobox用）   
        /// add2024-08-29 plq
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetTeachUserDic()
        {
            try
            {
                var list = new P_UserBLL().GetTeachUserDic();
                return this.Json(list);
            }
            catch
            {
                return this.Json("");
            }
        }

        /// <summary>
        /// 获取选择用户的带教医生数据(闵行移植参考)
        /// add2024-08-29 plq
        /// </summary>
        /// <returns></returns>
        [HttpPost]//获取人员
        public ActionResult GetUserGroup()
        {
            string workcode = Request.Form["WorkCode"];
            var list = new P_UserBLL().GetUserGroup(workcode);
            return Json(list, "appliction/json", JsonRequestBehavior.AllowGet);
        }


    }
}
